<template>
  <div class="info">
    <div class="allsearch">
      <section class="search-content">
        <el-row :gutter="4" type="flex" justify="start">
          <el-col :span="22">
            <el-select v-if="radio === 'passed'" v-model="option" @change="handleClick">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-input
              v-model="username"
              placeholder="活动名称"
              style="width:200px;"
              @keyup.enter.native="handleClick"
            />
            <el-button type="primary" @click="handleClick">搜索</el-button>
            <el-button size="medium" type="info" @click="clearParams">清空</el-button>
            <el-radio-group v-model="radio" size="medium" @change="handleClick">
              <el-radio label="passed" border>已通过</el-radio>
              <el-radio label="noPassed" border>未通过</el-radio>
              <el-radio label="audit" border>待审核</el-radio>
              <el-radio label="edit" border>编辑中</el-radio>
            </el-radio-group>
          </el-col>
          <el-col :span="2">
            <div style="float:right;">
              <el-button type="primary" @click="handlePush">创建打折活动</el-button>
            </div>
          </el-col>
        </el-row>
      </section>
    </div>
    <subtable
      :table-label="discountLabel"
      :table-data="discountData.slice((currentpage-1)*pagesize,currentpage*pagesize)"
    >
      <el-table-column slot="isEnd" :label="radio === 'passed' ? '活动状态' : '审核状态'" align="center" min-width="100">
        <template slot-scope="scope">
          <div v-if="radio === 'passed'">{{ scope.row.statusStr }}</div>
          <div v-if="radio !== 'passed'">{{ scope.row.auditStatusStr }}</div>
        </template>
      </el-table-column>

      <el-table-column slot="button" :min-width="100" label="操作" align="center">
        <template slot-scope="scope">
          <el-dropdown
            split-button
            trigger="click"
            type="primary"
            @click="getDetail(scope.row, 'view')"
            @command="handleCommand($event, scope.row)"
          >
            查看
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item type="primary" command="1">编辑</el-dropdown-item>
              <el-dropdown-item command="2">审核</el-dropdown-item>
              <el-dropdown-item command="3">删除</el-dropdown-item>
              <el-dropdown-item command="4">开启</el-dropdown-item>
              <el-dropdown-item command="5">结束</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </subtable>

    <pagination
      :total="total"
      :current-page="currentpage"
      :page-size="pagesize"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />
    <!-- 查看和审核弹窗 -->
    <dis-dialog
      :visiabledialog="disDialog"
      :dialog-data="dialogData"
      :audit="audit"
      @Visiable="disDialog = false,audit = '',dialogData = {}"
      @handleAudit="updateDiscount"
    />
  </div>
</template>

<script>
  import DisDialog from './components/discount/dialog'
  import Subtable from '@/components/Eltable'
  import Pagination from '@/components/Pagination' // 分页组件
  import {deleteDiscount, getCourseList, getDiscountList, updateDiscount} from '@/api/operate/discount' // 接口
  import {getTenantId} from '@/utils/auth'

  export default {
    components: {
      Subtable,
      Pagination,
      DisDialog
    },
    data() {
      return {
        audit: '',
        disDialog: false,
        dialogData: {},
        total: 0,
        currentpage: 1,
        pagesize: 10,
        discountLabel: [
          {
            label: '名称', width: '', prop: 'name'
          }, {
            label: '类型', width: '', prop: 'typeStr'
          }, {
            label: '打折对象', width: '', prop: 'targetObj'
          }, {
            label: '活动时间', width: '', prop: 'time'
          }
        ],
        discountData: [],
        listFilter: [],
        changedata: true,
        activeName: '1',
        username: '',
        radio: 'passed',
        option: '',
        options: [
          {
            label: '全部',
            value: ''
          },
          {
            label: '未开始',
            value: 'noBegin'
          },
          {
            label: '进行中',
            value: 'ongoing'
          },
          {
            label: '已结束',
            value: 'ended'
          }
        ]
      }
    },
    mounted() {
      this.getData()
    },
    methods: {
      handleCommand(command, row) {
        if (command === '1') {
          this.handlePush(row)
        } else if (command === '2') {
          this.getDetail(row, 'audit')
        } else if (command === '3') {
          this.deleteDiscount(row)
        } else if (command === '4') {
          row.status = 'ongoing'
          this.updateDiscount(row, '开启')
        } else if (command === '5') {
          row.status = 'ended'
          this.updateDiscount(row, '结束')
        }
      },
      handlePush(row) {
        if (row) {
          this.$router.push({name: 'Discount-create', params: row})
        } else {
          this.$router.push('/operate/discount-create')
        }
      },
      handleClick() {
        this.discountData = this.listFilter.filter(item => {
          if (this.radio && item.auditStatus !== this.radio) return false
          if (this.option && item.status !== this.option) return false
          if (this.username && item.name.toLocaleLowerCase().indexOf(this.username.toLocaleLowerCase()) === -1) return false
          return true
        })
        this.total = this.discountData.length
      },
      clearParams() {
        this.radio = ''
        this.option = ''
        this.username = ''
        this.getData()
      },
      getData() {
        this.listLoading = true
        getDiscountList().then(response => {
          this.discountData = response.data.items.filter(item => {
            if (item.tenantId !== getTenantId()) return false
            return true
          })
          this.discountData.map(item => {
            if (item.status === 'noBegin') item.statusStr = '未开始'
            if (item.status === 'ongoing') item.statusStr = '进行中'
            if (item.status === 'ended') item.statusStr = '已结束'
            if (item.auditStatus === 'passed') item.auditStatusStr = '已通过'
            if (item.auditStatus === 'noPassed') item.auditStatusStr = '未通过'
            if (item.auditStatus === 'audit') item.auditStatusStr = '待审核'
            if (item.auditStatus === 'edit') item.auditStatusStr = '编辑中'
            if (item.type === 'limitDiscount') item.typeStr = '限时打折'
            if (item.type === 'limitFree') item.typeStr = '限时免费'
            if (item.type === 'allDiscount') item.typeStr = '全站打折'
            if (item.startTime) item.startTimeStr = new Date(item.startTime).toLocaleString().replace(/[\u4e00-\u9fa5]/g, '')
            if (item.endTime) item.endTimeStr = new Date(item.endTime).toLocaleString().replace(/[\u4e00-\u9fa5]/g, '')
            item.time = '从' + item.startTimeStr + '至' + item.endTimeStr
            item.targetObj = (item.targetIds ? item.targetIds.split(',').length : 0) + ' ' + item.target
          })
          this.listFilter = this.discountData
          this.discountData = this.listFilter.filter(item => {
            if (this.radio && item.auditStatus !== this.radio) return false
            return true
          })
          this.total = this.discountData.length
        })
      },
      getDetail(row, event) {
        this.dialogData = Object.assign({}, row)
        if (this.dialogData.targetIds) {
          getCourseList(this.dialogData.targetIds).then(res => {
            this.dialogData.tableData = res.data.items
            if (event === 'audit') {
              this.audit = 'audit'
            }
            this.disDialog = true
          })
        } else {
          this.dialogData.tableData = []
          this.disDialog = true
        }
      },
      updateDiscount(row, event) {
        this.disDialog = false
        updateDiscount(row).then(res => {
          this.$notify({
            title: '成功',
            message: `折扣活动已${event}！`,
            type: 'success',
            duration: 2000
          })
          this.getData()
        })
      },
      deleteDiscount(row) {
        this.$confirm('确认删除该折扣活动', '删除', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warring'
        }).then(() => {
          deleteDiscount(row.id).then(res => {
            this.$notify({
              title: '成功',
              message: '折扣活动成功删除！',
              type: 'success',
              duration: 2000
            })
            this.getData()
          })
        }).catch(() => {
          this.$message.info('取消删除!')
        })
      },
      handleSizeChange(val) {
        this.currentpage = 1
        this.pagesize = val.value
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
      },
      handleCurrentChange(val) {
        this.currentpage = val.value
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
      }
    }
  }
</script>

<style lang="scss">
  .info {
    padding: 14px 20px;

    .allsearch {
      margin-top: 21px;
    }

    .addprogram {
      width: 100%;
      padding-bottom: 40px;

      .el-button {
        float: right;
      }

      .el-table .cell {
        white-space: pre-wrap;
      }
    }
  }
</style>
